package io.renren.modules.tag.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.lables.service.LabelService;
import io.renren.modules.meta.entity.EventEntity;
import io.renren.modules.meta.entity.SubjectEntity;
import io.renren.modules.meta.service.EventEntityService;
import io.renren.modules.meta.service.SubjectService;
import io.renren.modules.tag.entity.TagRulesEntity;
import io.renren.modules.tag.entity.TagsBasicInfoEntity;
import io.renren.modules.tag.service.TagRulesService;
import io.renren.modules.tag.service.TagsBasicInfoService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 标签规则表
 *
 * @author linyuan
 * @email linyuan@gmail.com
 * @date 2023-08-20 21:32:02
 */
@RestController
@RequestMapping("tag/tagrules")
public class TagRulesController {
    @Autowired
    private TagRulesService tagRulesService;
    @Autowired
    private LabelService labelService;
    @Autowired
    private TagsBasicInfoService tagsBasicInfoService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private EventEntityService eventEntityService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("tag:tagrules:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils pageUtils = tagRulesService.queryPage(params);
        List<?> list = pageUtils.getList();
        HashMap<Integer, JSONObject> integerObjectHashMap = new HashMap<>();
        for (Object o : list) {
            TagRulesEntity tagRulesEntity = (TagRulesEntity) o;
            Integer tagInfoId = tagRulesEntity.getTagInfoId();
            JSONObject json = integerObjectHashMap.get(tagInfoId);
            if (json == null) {
                json = new JSONObject();
                integerObjectHashMap.put(tagInfoId, json);
                json.put("tagCreateWay", tagRulesEntity.getTagCreateWay());
                json.put("tagCreateName", getCreateName(tagRulesEntity.getTagCreateWay()));
                JSONObject tagsBasicInfo = new JSONObject();
                TagsBasicInfoEntity basicInfoEntity = tagsBasicInfoService.getById(tagRulesEntity.getTagInfoId());
                tagsBasicInfo.put("subjectId", basicInfoEntity.getSubjectId());
                tagsBasicInfo.put("subjectName", basicInfoEntity.getSubjectName());
                tagsBasicInfo.put("displayName", basicInfoEntity.getDisplayName());
                tagsBasicInfo.put("tagName", basicInfoEntity.getTagName());
                tagsBasicInfo.put("tagGroup", basicInfoEntity.getTagGroup());
                tagsBasicInfo.put("notes", basicInfoEntity.getNotes());
                json.put("tagsBasicInfo", tagsBasicInfo);
            }
            JSONArray layeringList = (JSONArray) json.get("layeringList");
            if (layeringList == null) {
                layeringList = new JSONArray();
                json.put("layeringList", layeringList);
            }
            JSONObject layering = null;
            String levelName = tagRulesEntity.getLevelName();
            for (int i = 0; i < layeringList.size(); i++) {
                JSONObject obj = layeringList.getJSONObject(i);
                if (obj.getString("levelName").equals(levelName)) {
                    layering = obj;
                    break;
                }
            }
            if (layering == null) {
                layering = new JSONObject();
                layering.put("levelName", levelName);
                layering.put("levelDescription", tagRulesEntity.getLevelDescription());
                layering.put("op", tagRulesEntity.getOp());
                layeringList.add(layering);
            } else {
                Integer tagCreateMode = tagRulesEntity.getTagCreateMode();
                if (tagCreateMode == 1) {
                    Object rules = layering.get("attributesRules");
                    if (rules == null) {
                        rules = new JSONArray();
                        layering.put("attributesRules", rules);
                    }
                    JSONObject attributesRule = new JSONObject();
                    attributesRule.put("op", tagRulesEntity.getOp());
                    attributesRule.put("propertyName", tagRulesEntity.getPropertyName());
                    attributesRule.put("propertyId", tagRulesEntity.getPropertyId());
                    attributesRule.put("valueType", tagRulesEntity.getValueType());
                    attributesRule.put("relation", tagRulesEntity.getRelation());
                    attributesRule.put("value", tagRulesEntity.getValue());
                    attributesRule.put("mode",tagRulesEntity.getTagCreateMode());
                    ((JSONArray) rules).add(attributesRule);
                } else {
                    Object rules = layering.get("behaviorRules");
                    if (rules == null) {
                        rules = new JSONArray();
                        layering.put("behaviorRules", rules);
                    }
                    JSONObject behaviorRule = new JSONObject();
                    behaviorRule.put("op", tagRulesEntity.getOp());
                    behaviorRule.put("propertyName", tagRulesEntity.getPropertyName());
                    behaviorRule.put("propertyId", tagRulesEntity.getPropertyId());
                    behaviorRule.put("valueType", tagRulesEntity.getValueType());
                    behaviorRule.put("relation", tagRulesEntity.getRelation());
                    behaviorRule.put("value", tagRulesEntity.getValue());
                    behaviorRule.put("mode",tagRulesEntity.getTagCreateMode());
                    ((JSONArray) rules).add(behaviorRule);
                }
            }
        }
        JSONArray jsonData = new JSONArray();
        for (Integer integer : integerObjectHashMap.keySet()) {
            jsonData.add(integerObjectHashMap.get(integer));
        }
        return R.ok().put("page", jsonData.toJSONString());
    }

    private String getCreateName(Integer tagCreateWay) {
        switch (tagCreateWay) {
            case 1:
                return "自定义";
            case 2:
                return "基础指标值";
                case 3:
                return "基础指标值";
                case 4:
                return "行为结果分布";
                case 5:
                return "首末次特征";
            default:
                return "自定义";
        }
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("tag:tagrules:info")
    public R info(@PathVariable("id") Integer id) {
        TagRulesEntity tagRules = tagRulesService.getById(id);
        return R.ok().put("tagRules", tagRules);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("tag:tagrules:save")
    public R save(@RequestBody TagRulesEntity tagRules) {
        tagRulesService.save(tagRules);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("tag:tagrules:update")
    public R update(@RequestBody TagRulesEntity tagRules) {
        tagRulesService.updateById(tagRules);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("tag:tagrules:delete")
    public R delete(@RequestBody Integer[] ids) {
        tagRulesService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 删除
     */
    @PostMapping("/load/{id}")
    @RequiresPermissions("tag:tagrules:save")
    public R load(@PathVariable("id") Integer id) {
//        HashMap<String, List<TagRulesEntity>> stringListHashMap = labelService.saveBatch(id);
        HashMap<String, List<TagRulesEntity>> stringListHashMap = new HashMap<>();
        return R.ok().put("tagRules", stringListHashMap);
    }
    
    /**
     * 删除
     */
    @PostMapping("/circleSelect/{levelName}")
    @RequiresPermissions("tag:tagrules:save")
    public R load(@PathVariable("levelName") String levelName) {
        String[] tags={levelName};
        HashMap<String, List<String>> users = labelService.circleSelect(tags);
        return R.ok().put("users", users);
    }
    @PostMapping("/profile/{subject}/{userid}")
    @RequiresPermissions("tag:tagrules:save")
    public R profile(@PathVariable("subject") String subject,@PathVariable("userid") Long userid) {
        QueryWrapper<SubjectEntity> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("subject_name", subject);
        SubjectEntity subjectEntity = subjectService.getOne(subjectQueryWrapper);
        QueryWrapper<EventEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("subject_table", subjectEntity.getSubjectTable()).eq("subject_id", userid);
        List<EventEntity> events = eventEntityService.list(queryWrapper);
        for (EventEntity event : events) {
            System.out.println(event);
        }
        ArrayList<String> subjectTags = labelService.getSubjectTags(subject, userid);
        for (String subjectTag : subjectTags) {
            System.out.println(subjectTag);
        }
        return R.ok().put("users", events);
    }
}
